package com.blog.jdo;

import java.util.Collection;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import javax.jdo.Transaction;

import com.blog.model.Blog;

public class BlogDAO {
	private static final Logger log = Logger.getLogger(Blog.class.getName());
	
	public Blog addBlog(final Blog blog) {
		final String logString = "addBlog( " + blog + " )";
		log.finest(logString + " - begin");
		Blog retVal = null;
		final PersistenceManager pm = PMF.get().getPersistenceManager();
		final Transaction tx = pm.currentTransaction();
		try {
			tx.begin();
			retVal = pm.makePersistent(blog);
			tx.commit();
		}
		catch (final Exception e) {
			log.log(Level.SEVERE, logString + " - exception", e);
			throw new RuntimeException(e);
		}
		finally {
			if (tx.isActive()) {
				tx.rollback();
			}
			pm.close();
		}
		log.finest(logString + " - end ( returning: " + retVal + " )");
		return retVal;
	}
	
	public void deleteBlog(final Blog blog) {
		final String logString = "deleteBlog( " + blog + " )";
		log.finest(logString + " - begin");
		final PersistenceManager pm = PMF.get().getPersistenceManager();
		final Transaction tx = pm.currentTransaction();
		try {
			tx.begin();
			pm.deletePersistent(blog);
			tx.commit();
		}
		catch (final Exception e) {
			log.log(Level.SEVERE, logString + " - exception", e);
			throw new RuntimeException(e);
		}
		finally {
			if (tx.isActive()) {
				tx.rollback();
			}
			pm.close();
		}
		log.finest(logString + " - end");
	}
	
	@SuppressWarnings("unchecked")
	public Collection<Blog> getBlogs() {
		final String logString = "getBlogs()";
		log.finest(logString + " - begin");
		Collection<Blog> retVal;
		final PersistenceManager pm = PMF.get().getPersistenceManager();
		final Transaction tx = pm.currentTransaction();
		try {
			tx.begin();
			final Query q = pm.newQuery(Blog.class);
			final Collection<Blog> result = (Collection<Blog>) q.execute();
			retVal = result;
			tx.commit();
		}
		catch (final Exception e) {
			log.log(Level.SEVERE, logString + " - exception", e);
			throw new RuntimeException(e);
		}
		finally {
			if (tx.isActive()) {
				tx.rollback();
			}
			pm.close();
		}
		log.finest(logString + " - end ( returning: " + retVal + " )");
		return retVal;
	}
	
}
